package com.ts.manager;

import com.rio.core.L;
import com.rio.helper.Sleeper;
import com.rio.layout.TaskManager;
import com.rio.layout.view.SimpleTask;
import com.ts.host.Event;
import com.ts.host.N;

import de.greenrobot.event.EventBus;

public abstract class WaterTask extends SimpleTask {

	public static final int PAUSE_TIME = 100;

	public static final int CLICK_TIME = 500;

	public static final int WATER_DEFAULT = 12;

	private long last;

	private int progress;

	private boolean start = false;

	private int second;

	public abstract void openWater();

	public abstract void closeWater();

	protected void onProgress(int progress, long total) {
	};

	protected void onStop(int progress, long total) {
	};

	protected int onStart(int key,int total) {
		return 1;
	};

	protected boolean onKeyEvent(int key) {
		return false;
	}

	public void setSecond(int second) {
		this.second = second;
	}

	@Override
	public Object onBGThread(Object... params) throws Exception {
		openWater();
		int time = second * 10;
		for (; progress < time; progress++) {
			Sleeper.sleep(PAUSE_TIME);
			onProgress(progress, time);
			if (!start)
				break;
		}
		closeWater();
		onStop(progress, time);
		start = false;
		return null;
	}

	public void stop() {
		start = false;

	}
	
	public void reset(){
		start = false;
		progress = 1;
		last = 0;
		second = WATER_DEFAULT;
	}

	public void handle(int key) {

		long time = System.currentTimeMillis();
		if (time - last > CLICK_TIME || last == 0) {
			if (!onKeyEvent(key)) {
				if (start) {
					stop();
				} else {
					last = time;
					start = true;
					progress = onStart(key,second * 10);
					TaskManager.getInstance().async(this);

				}
			}
		} else {
			last = time;
		}

	}

}
